local scene = director:createScene()

function scene:setUp(event)
    dbg.print("sceneGame:setUp")
	
	local scaleX = 320/director.displayWidth
	local scaleY = 480/director.displayHeight
	
	audio:loadStream("sound/explosion.mp3", false)
	
	local levelText = director:createLabel({x=director.displayCenterX/2, 
	y=director.displayHeight-50/scaleY, text="Level: ", zOrder=2, 
	hAlignment="center", xAnchor=0.5, color=color.white, xScale=1/scaleX, yScale=1/scaleY})
	
	local levelTextNumber = director:createLabel({x=levelText.x+50/scaleX, 
	y=director.displayHeight-50/scaleY, text="", zOrder=2, hAlignment="center", 
	xAnchor=0.5, color=color.white, xScale=1/scaleX, yScale=1/scaleY})
	
	local livesText = director:createLabel({x=director.displayCenterX+director.displayCenterX/2, 
	y=director.displayHeight-50/scaleY, text="Lives: ", zOrder=2, hAlignment="center", xAnchor=0.5, 
	color=color.white, xScale=1/scaleX, yScale=1/scaleY})
	
	local livesTextNumber = director:createLabel({x=livesText.x+50/scaleX, 
	y=director.displayHeight-50/scaleY, text="", zOrder=2, hAlignment="center", 
	xAnchor=0.5, color=color.white, xScale=1/scaleX, yScale=1/scaleY})
	
	local changeLevelLabel = director:createLabel({x=director.displayCenterX, y=290/scaleY, text="", 
	zOrder=2, hAlignment="center", xAnchor=0.5, color=color.green, isVisible=false, xScale=1/scaleX, yScale=1/scaleY})
	
	local planets = director:createAtlas( {width=91, height=91, numFrames=20, 
	textureName="img/planets.png",} )
	
	local planetAnimation = director:createAnimation( {start=1, count=20, 
	atlas=planets, delay=3,} )
	
	local planet = director:createSprite( { x=director.displayCenterX, y=0, 
	xAnchor=0.5, yAnchor=0, source=planetAnimation, xScale=.8/scaleX,yScale=.9/scaleY, zOrder=1,} )
	physics:addNode(planet, {type="dynamic", isSensor = true,})
	planet.physics.radius = planet.h/2
	
	comet = {};
	math.randomseed (os.time ())
	
	for i = 1, 30 do
		comet[i] = director:createSprite(0 ,-200/scaleY ,"img/comet.png")
		comet[i].xAnchor=0.5; comet[i].yAnchor=0
		comet[i].zOrder = 0
		comet[i].name = "comet "..i
		physics:addNode(comet[i], {isSensor = true, type="dynamic",})
		comet[i].physics.radius = comet[i].w/2
	end

	local cometNumber = 3
	local levelNumber = 1
	local isTouching = false;
	local levelTime = 60;
	local startSpeed = .5/scaleY
	local livesNumber = 5
	local gameRun = 1;
		
		system.debugTime = nil
		system.gameTime = 0
		system.timers = {}
	
	function system:getTime()
		if self.debugTime then
			return self.debugTime
		else
			return self.gameTime
		end
	end

	local move = function()
	
		if (livesNumber > 0) then
			if (system:getTime() >= levelTime) then
				changeLevelLabel.isVisible = false
				levelTime = levelTime + 60
				levelNumber = levelNumber + 1
				startSpeed = startSpeed + .3/scaleY
				planet.xScale = planet.xScale+.2/scaleX
				planet.yScale = planet.yScale+.2/scaleY
			end
			if(system:getTime() <= levelTime-57 and system:getTime() >= levelTime-60) then
				changeLevelLabel.text = "Level: "..levelNumber
				changeLevelLabel.isVisible = true
				else
				changeLevelLabel.isVisible = false
			end
			levelTextNumber.text = levelNumber
			livesTextNumber.text = livesNumber
			elseif (livesNumber == 0) then
			--lose
			livesNumber = -1
			livesTextNumber.text = 0
			local buttonBack = director:createSprite(director.displayCenterX, 50/scaleY, "img/button.png")
			buttonBack.xAnchor=0.5; buttonBack.yAnchor=0.5; buttonBack.xScale=.7/scaleX; buttonBack.yScale=.5/scaleY; buttonBack.zOrder=3;
			local labelBack = director:createLabel({x=25, y=35, text="Restart", zOrder = 3, hAlignment="left", color=color.black,})
			buttonBack:addChild(labelBack); labelBack.xScale=1.3; labelBack.yScale=1.5
			
			local scoreRectangle = director:createRectangle( { x=director.displayCenterX, y=director.displayCenterY, w=200/scaleX, h=200/scaleY, color=color.teal, zOrder = 4, strokeColor=color.black, xAnchor=.5, yAnchor=.5,} )
			local gameOverRectangle = director:createLabel({x=scoreRectangle.x, y=scoreRectangle.y+scoreRectangle.h/3, text="GAME OVER!", zOrder = 5, hAlignment="center", xAnchor=0.5, color=color.black, xScale=1/scaleX, yScale=1/scaleY})
			local levelTitleRectangle = director:createLabel({x=scoreRectangle.x, y=scoreRectangle.y, text="Your level is:", zOrder = 5, hAlignment="center", xAnchor=0.5, color=color.black, xScale=1/scaleX, yScale=1/scaleY})
			local levelTextRectangle = director:createLabel({x=scoreRectangle.x, y=scoreRectangle.y-scoreRectangle.h/3, text=levelNumber, zOrder = 5, hAlignment="center", xAnchor=0.5, color=color.black, xScale=1/scaleX, yScale=1/scaleY})
	
			local file = io.open("levelrecord.txt")
			levelListOne = tonumber(file:read())
			levelListTwo = tonumber(file:read())
			levelListThree = tonumber(file:read())
			levelListFour = tonumber(file:read())
			levelListFive = tonumber(file:read())
			file:close()
				
			if (levelNumber > levelListOne) then
				levelTitleRectangle.text = "RECORD LEVEL:"
				levelListFive = levelListFour
				levelListFour = levelListThree
				levelListThree = levelListTwo
				levelListTwo = levelListOne
				levelListOne = levelNumber
				elseif (levelNumber > levelListTwo) then
					levelTitleRectangle.text = "RECORD LEVEL:"
					levelListFive = levelListFour
					levelListFour = levelListThree
					levelListThree = levelListTwo
					levelListTwo = levelNumber
						elseif (levelNumber > levelListThree) then
						levelTitleRectangle.text = "RECORD LEVEL:"
						levelListFive = levelListFour
						levelListFour = levelListThree
						levelListThree = levelNumber
							elseif (levelNumber > levelListFour) then
							levelTitleRectangle.text = "RECORD LEVEL:"
							levelListFive = levelListFour
							levelListFour = levelNumber
								elseif (levelNumber > levelListFive) then
								levelTitleRectangle.text = "RECORD LEVEL:"
								levelListFive = levelNumber
			end
				
			file = io.open("levelrecord.txt", "w")
			file:write(levelListOne.."\n")
			file:write(levelListTwo.."\n")
			file:write(levelListThree.."\n")
			file:write(levelListFour.."\n")
			file:write(levelListFive.."\n")
			file:close()
			
			function buttonBack:touch(event)
				if (event.phase == 'began') then
					for i = 1, 30 do
						physics:removeNode(comet[i])
						comet[i]:removeFromParent()
					end
					gameRun = 0
					comet = {}
					levelTextNumber:removeFromParent()
					labelBack:removeFromParent()
					buttonBack:removeFromParent()
					scoreRectangle:removeFromParent()
					levelTitleRectangle:removeFromParent()
					gameOverRectangle:removeFromParent()
					levelTextRectangle:removeFromParent()
					levelText:removeFromParent()
					livesText:removeFromParent()
					livesTextNumber:removeFromParent()
					changeLevelLabel:removeFromParent()
					physics:removeNode(planet)
					planet:removeFromParent()
					collectgarbage("collect")
					director:cleanupTextures()
					system:sendEvent("moveToSceneMenu")
				end
			end
			buttonBack:addEventListener('touch', buttonBack)
			
		end
		
		if (gameRun == 1) then
			if (levelNumber <= 10) then
				cometNumber = levelNumber * 3
			end
			
			for i = 1, cometNumber do
				if (comet[i].y <= 0) then
					comet[i].y = math.random(director.displayHeight, director.displayHeight+100)
					comet[i].x = math.random(director.displayCenterX-planet.w/2/scaleX, director.displayCenterX+planet.w/2/scaleX)
					comet[i].xScale = (math.random(20, 50)/100)/scaleX
					comet[i].yScale = (math.random(20, 50)/100)/scaleY
					comet[i].speed = startSpeed + math.random(50, 200)/100
					else
					comet[i].y = comet[i].y - comet[i].speed
				end
			end
		end
	end
	system:addEventListener("update", move)
	
	local onTouch = function(event)
		local cometTouch = event.target
		if (event.phase == "began") then 
			if (cometTouch ~= nil) then
				cometTouch.y = - 200
			end
		end
	end
	for i = 1, 30 do
	comet[i]:addEventListener("touch", onTouch)
	end
    system:addEventListener("touch", onTouch)
	
	local function onCollision( event )
		if ( event.phase == "began" ) then
			if (livesNumber > 0) then
				livesNumber = livesNumber - 1
				audio:playStream("sound/explosion.mp3", false)
			end
		elseif ( event.phase == "ended" ) then
		end
	end
	planet:addEventListener( "collision", onCollision )
	
end

function scene:tearDown(event)
    dbg.print("sceneGame:tearDown")
end

scene:addEventListener({"setUp", "tearDown"}, scene)
return scene -- We must return the scene object!